package com.manager.user.web.controller;

import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.manager.core.shiro.config.ShiroUtil;
import com.manager.core.web.controller.BaseController;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.manager.commons.base.SessionUser;

/**
 * 后台管理控制器
 *
 * @author H
 */
public abstract class AdminController<T> extends BaseController<T> {
    public Map<String, Object> _map = new HashMap<>();
    protected static ResourceBundle bundler = null;
    private static String resUrl = "";

    static {
        bundler = ResourceBundle.getBundle("website");
        resUrl = bundler.getString("res.url");
    }

    /**
     * 授权登录异常
     */
    @ExceptionHandler({AuthenticationException.class})
    public ModelAndView authenticationException() {
        return new ModelAndView("error/403.ftl");
    }

    protected T getParamsModel() {
        Map<String, Object> maps = getParams();
        return JSONObject.parseObject(JSONObject.toJSONString(maps), entityClass, Feature.OrderedField);
    }


    /**
     * 获取参数
     *
     * @return
     */
    protected Map<String, Object> getParams() {
        Map<String, Object> maps = super.getParams();
        maps.put("creator", getUserId());
        return maps;
    }

    protected String getUserId() {
        SessionUser pu = getUserSession();
        if (null != pu) {
            return pu.getUserPkid();
        }
        return null;
    }

    /**
     * 获取ModelAndView对象
     *
     * @param path
     * @return
     */
    protected ModelAndView getModelAndView(String path) {
        ModelAndView model = new ModelAndView(path);
        if (ShiroUtil.isAuthenticated()) {
            _map.putAll(getParams());
            request.setAttribute("map", _map);
        }
        request.setAttribute("resUrl", resUrl);
        return model;
    }

    /**
     * 获取ModelAndView对象
     *
     * @param path
     * @return
     */
    protected ModelAndView getModelAndView(String path, Object info) {
        request.setAttribute("info", info);
        return getModelAndView(path);
    }


    /**
     * 获取参数如果为null则返回空字符串
     *
     * @param params
     * @param key
     * @return
     */
    public String getParamsString(Map<String, Object> params, String key) {
        if (params.containsKey(key)) {
            Object value = params.get(key);
            if (value != null) {
                return String.valueOf(value);
            }
            return "";
        } else {
            return "";
        }
    }
}